package com.lhl.forum.controller;

import com.lhl.forum.common.AppResult;
import com.lhl.forum.common.ResultCode;
import com.lhl.forum.config.AppConfig;
import com.lhl.forum.exception.ApplicationException;
import com.lhl.forum.model.Article;
import com.lhl.forum.model.Board;
import com.lhl.forum.model.User;
import com.lhl.forum.service.IArticleService;
import com.lhl.forum.service.IBoardService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Api(tags = "文章接口")
@Slf4j
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Resource
    private IBoardService boardService;

    @Resource
    private IArticleService articleService;

    /**
     * 发布帖子
     * @param request
     * @param boardId  版块id
     * @param title    文章标题
     * @param content  文章正文
     * @return
     */
    @ApiOperation("发布文章")
    @PostMapping("/create")
    public AppResult create(HttpServletRequest request,
                            @ApiParam("版块id") @RequestParam("boardId") @NonNull Long boardId,
                            @ApiParam("文章标题") @RequestParam("title") @NonNull String title,
                            @ApiParam("文章正文") @RequestParam("content") @NonNull String content){

        HttpSession session = request.getSession(false);
        User user = (User)session.getAttribute(AppConfig.USER_SESSION);

        //校验用户状态
        if (user.getState() == 1){
            //用户被禁言
            //打印日志
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            //返回
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        //校验版块是否存在
        Board board = boardService.selectById(boardId);
        if (board == null || board.getState() == 1 || board.getDeleteState() == 1){
            //打印日志
            log.warn(ResultCode. FAILED_BOARD_BANNED.toString());
            //返回
            return AppResult.failed(ResultCode. FAILED_BOARD_BANNED);
        }

        //封装数据
        Article article = new Article();
        article.setBoardId(boardId);
        article.setTitle(title);
        article.setContent(content);
        article.setUserId(user.getId());

        //调用service
        articleService.create(article);

        //响应
        return AppResult.success();
    }

    /**
     * 获取所有帖子列表（不包含正文）
     * @param boardId
     * @return
     */
    @ApiOperation("获取帖子列表")
    @GetMapping("/getByBoardId")
    public AppResult getByBoardId(@ApiParam("版块id") @RequestParam(name = "boardId",required = false) Long boardId){

        List<Article> articles;

        //判断是否传入版块id
        if (boardId == null){
            //没有传入版块Id
            //调用service
            articles = articleService.selectAll();
        }else {
            //传入版块id
            //调用service
            articles = articleService.selectById(boardId);
        }

        if (articles == null){
            articles = new ArrayList<>();
        }

        return AppResult.success(articles);
    }

    /**
     * 根据帖子id获取详情（(访问帖子详情)）
     * @param id 帖子id
     * @return
     */
    @ApiOperation("根据帖子id获取详情")
    @GetMapping("/details")
    public AppResult<Article> details(HttpServletRequest request,
                                  @ApiParam("帖子id") @RequestParam("id") @NonNull Long id){
        HttpSession session = request.getSession(false);
        //获取当前用户的用户名
        User user = (User)session.getAttribute(AppConfig.USER_SESSION);

        //获取详情
        Article article = articleService.selectDetailById(id);

        //帖子是否存在
        if (article == null){
            //返回帖子异常信息
            return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }

        //判断当前用户是否是作者
        if (user.getId() == article.getUserId()){
            //当前用户是作者
            article.setOwn(true);
        }else {
            article.setOwn(false);

        }

        //返回结果
        return AppResult.success(article);
    }

    @ApiOperation("修改帖子")
    @PostMapping("/modify")
    public AppResult modify(HttpServletRequest request,
                            @ApiParam("帖子id") @RequestParam("id") @NonNull Long id,
                            @ApiParam("帖子标题") @RequestParam("title") @NonNull String title,
                            @ApiParam("帖子内容") @RequestParam("content") @NonNull String content){

        //判断用户是否有权限修改
        //从session中拿到用户信息
        HttpSession session = request.getSession(false);
        User user = (User)session.getAttribute(AppConfig.USER_SESSION);

        //判断用户的状态
        if (user.getDeleteState() == 1){
            //打印日志
            log.warn(ResultCode.FAILED_FORBIDDEN.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_FORBIDDEN));
        }

        //根据帖子id去查询帖子信息
        Article article = articleService.selectByArticledId(id);
        //判断帖子是否存在
        if (article == null){
            //返回错误描述
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }


        //判断帖子状态是否正常
        if (article.getState() == 1 || article.getDeleteState() == 1){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }

        //判断用户是否是作者
        if (user.getId() != article.getUserId()){
            //打印日志
            log.warn(ResultCode.FAILED_FORBIDDEN.toString() + "您不是作者，没有权限对该帖子进行修改");
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }

       // 打印日志
        log.info("帖子更新成功. Article id = " + id + "User id = " + user.getId() + ".");

        //更新帖子
        articleService.modify(id,title,content);

        return AppResult.success("更新帖子成功");
    }

    @ApiOperation("更新帖子点赞数")
    @PostMapping("/thumbsUp")
    public AppResult thumbsUp(HttpServletRequest request,@ApiParam("帖子id") @RequestParam("id") @NonNull Long id){
        //判断用户是否能够点赞
        HttpSession session = request.getSession(false);
        User user = (User)session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1){
            //用户处于禁言状态
            //打印日志
            log.warn(ResultCode.FAILED_USER_BANNED .toString());
            //返回结果
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        //判断帖子是否正常
        Article article = articleService.selectByArticledId(id);
        if (article == null || article.getState() == 1){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }

        //更新帖子的点赞数
        articleService.thumbsUp(id);


        //返回结果
        return AppResult.success("点赞成功！");
    }



    @ApiOperation("删除帖子")
    @PostMapping("/delete")
    public AppResult deleteById(HttpServletRequest request,@ApiParam("帖子id") @RequestParam("id") @NonNull Long id){
        //查询用户
        HttpSession session = request.getSession(false);
        User user = (User)session.getAttribute(AppConfig.USER_SESSION);

        //判断当前用户的状态
        if (user.getState() == 1){
            //用户被禁言
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        //查询帖子
        Article article = articleService.selectByArticledId(id);

        //判断帖子状态
        if (article == null || article.getState() == 1){
            //帖子状态异常
            return  AppResult.failed(ResultCode. FAILED_ARTICLE_BANNED);
        }

        //判断当前用户是不是作者
        if (user.getId() != article.getUserId()){
            //用户不是作者
            return AppResult.failed(ResultCode. FAILED_UNAUTHORIZED);
        }

        //删除帖子
        articleService.deleteById(id);

        log.info("帖子删除成功,articleId = " + id + ", UserId = " + user.getId());
        return AppResult.success("帖子删除成功");
    }










}
